<template>
  <div id="preview">
    <el-dialog :visible.sync="$parent.previewDialogVisible" title="" width="480px"
               append-to-body @closed='closeDialog' @open='openDialog' @opened="openedDialog">
      <el-row style="margin-bottom: 5px">
        <div style="margin: 10px;font-size: large;font-weight: bold;">
          <div style="margin-left: 5px;display: inline-block" v-html="formulaName">
          </div>
        </div>
      </el-row>
      <el-row v-if="name" style="margin-bottom: 5px">
        <div class="nick_name_block_cls">
          <div style="display: inline-block;margin-left: 10px">又称:
          </div>
          <div style="margin-left: 5px;display: inline-block" v-html="name">
          </div>
        </div>
      </el-row>
      <el-row v-if="formulaExplain">
        <div style="margin-left: 5px;color: red">
          <div style="margin-left: 5px;display: inline-block">*</div>
          <div style="display: inline-block" v-html="formulaExplain"></div>
        </div>
      </el-row>
      <el-radio-group v-if="type !== 3" v-model="activePanel" fill="#2DB7A0">
        <el-radio-button label="calculate">计算</el-radio-button>
        <el-radio-button label="describe">说明</el-radio-button>
      </el-radio-group>

      <div v-show="activePanel === 'calculate' ">

        <!-- 计算型 -->
        <el-row v-if="type === 1" style="margin: 10px">
          <div>
            <div class="cal-tip"></div>
            <div class="cal-text-cls">
              公式计算
            </div>
          </div>
          <div v-cloak v-if="medicalCalculatorData.length > 1" style="margin: 15px">
            <div>请选择:</div>
            <el-radio v-for="(item, idx) in medicalCalculatorData" :key="idx" v-model="selectedFormulaExpressionIdx"
                      :label="idx" style="margin: 10px; ">
              <span v-html="item.explain"></span>
            </el-radio>
          </div>
          <!-- 列项 -->
          <div v-for="(mcdItem, idx) in medicalCalculatorData" v-cloak :key="idx" :label="idx">
            <div v-if="idx === selectedFormulaExpressionIdx">

              <div v-for="(item, idx) in mcdItem.calculateData.formulaItems" :key="item.item_id" class="lx-text-cls">
                <div>
                  <span v-if="mcdItem.calculateData.formulaItems.length>1">{{ idx + 1 }}.</span>
                  <span v-if="item.item_name" v-html="item.item_name"></span>
                  <span v-if="item.item_unit" v-html="'(' + item.item_unit + ')'"></span>
                </div>
                <el-input-number v-model="item.item_value" :controls="false" style="margin: 10px;"></el-input-number>
              </div>
            </div>
          </div>
        </el-row>

        <!-- 评分型 -->
        <el-row v-else-if="type === 2" style="margin: 10px">
          <div>
            <div class="score-tip"></div>
            <div class="score-text-cls">评分计算</div>
          </div>

          <div v-cloak v-if="calculatorSore.length > 1" style="margin: 15px">
            <div>请选择:</div>
            <el-radio v-for="(item, idx) in calculatorSore" :key="idx" v-model="selectedFormulaExpressionIdx"
                      :label="idx" style="margin: 10px; ">
              <span v-html="item.explain"/>
            </el-radio>
          </div>

          <div v-for="(mcdItem, idx) in calculatorSore" v-cloak :key="idx" :label="idx">
            <div v-if="idx === selectedFormulaExpressionIdx">

              <div v-for="(questionItem, idx) in mcdItem.scoreData" :key="questionItem.id" style="margin: 15px">
                <span v-if="mcdItem.scoreData.length>1">{{ (idx + 1) }}.</span>
                <span style="font-size: 16px; vertical-align: bottom"
                      v-html=" questionItem.name + (questionItem.multiple ? '(多选)' : '(单选)')"></span>
                <div v-if="!questionItem.multiple">
                  <el-radio-group v-model="questionItem.checkId">
                    <el-radio v-for="(optionItem, optionIdx) in questionItem.items"
                              :key="optionIdx"
                              :label="optionItem.id.toString()"
                              style="display: flex; margin: 10px;word-break: break-all;white-space: normal;">
                      <span v-html="optionItem.describe" style="line-height: 2"></span>
                    </el-radio>
                  </el-radio-group>
                </div>
                <div v-else>
                  <el-checkbox-group v-model="questionItem.checkList">
                    <el-checkbox v-for="(optionItem, optionIdx) in questionItem.items"
                                 :key="optionIdx"
                                 :label="optionItem.id"
                                 style="display: flex; margin: 10px;word-break: break-all;white-space: normal;">
                      <span v-html="optionItem.describe" style="line-height: 2"></span>
                    </el-checkbox>
                  </el-checkbox-group>
                </div>
              </div>
            </div>
          </div>

        </el-row>

        <el-row v-if="type != 3" style="margin: 10px">
          <div>
            <div class="cal-result-tip"></div>
            <div class="cal-result-text-cls">
              计算结果
            </div>
          </div>
          <div v-cloak style="margin: 15px">
            <div v-if="calculateResultDisplay">
              <span v-html="calculateResult"/>
              <span v-if="type == 1"
                    v-html="medicalCalculatorData[selectedFormulaExpressionIdx].calculateData.resultUnit"></span>
              <span v-if="resultFontColor" :style="{'color': resultFontColor}" v-html="'('+resultExplanation+')'"/>
            </div>
            <div>
              <el-button class="cal-btn-class" @click="calculate">
                {{ calculateResultDisplay ? '重新计算' : '点击计算' }}
              </el-button>
            </div>
            <div class="warning-text-cls">
              *所有计算结果必须重新核对，且不能作为临床决策的唯一依据
            </div>
          </div>
        </el-row>
      </div>


      <div v-show="activePanel === 'describe' ">
        <el-row style="margin: 10px">
          <div class="desc-tip"></div>
          <div class="desc-text-cls" v-html="type === 3 ? '描述' : '计算方法'">
          </div>
          <div id="describeContentDiv" style="margin: 15px" v-html="describeContent">
          </div>
        </el-row>
        <el-dialog ref="imgDialog" :append-to-body="true" :destroy-on-close="true" :modal="false"
                   :visible.sync="photoVisible"
                   style="text-align: center" width="70%" @closed='cleanDialog'>
          <img :src="url" width="80%">
        </el-dialog>
        <el-row style="margin: 10px">
          <div>
            <div class="result-desc-tip"></div>
            <div class="result-desc-text-cls">
              结果说明
            </div>
          </div>
          <div id="resultDescriptionDiv" style="margin: 15px" v-html="resultDescription">
          </div>
        </el-row>

        <el-row style="margin: 10px">
          <div>
            <div class="reference-tip"></div>
            <div class="reference-text-cls">
              参考文献
            </div>
          </div>
          <div v-cloak class="reference-content" style="white-space: normal" v-html="reference"></div>
        </el-row>
      </div>
    </el-dialog>
  </div>
</template>

<script>
let resultColorMap = {
  default: 'gray',
  normal: 'green',
  excess: 'orange',
  serious: 'red'
}
export default {

  methods: {
    openDialog() {
      this.calculateResultDisplay = false
      if (this.type == 3) {
        this.activePanel = 'describe'
      } else {
        this.activePanel = 'calculate'
      }
      this.resultFontColor = ''
      this.calculateResult = 0
      this.resultExplanation = ''
      this.selectedFormulaExpressionIdx = 0

      for (let field of this.fields) {
        if (field.name == '公式名称') {
          this.formulaName = field.property
        } else if (field.name == '结果说明') {
          this.resultDescription = field.property
        } else if (field.name == '参考文献') {
          this.reference = field.property
        } else if (field.name == '又称') {
          this.name = field.property.map(item => item).join(";");
        } else if (field.name == '公式说明') {
          this.formulaExplain = field.property
        }
      }
      if (!this.formulaName) {
        this.formulaName = ''
      }
      if (!this.resultDescription) {
        this.resultDescription = '无'
      }
      if (!this.reference) {
        this.reference = '无'
      }
      for (let item of this.calculatorSore) {
        if (item.scoreData) {
          for (let question of item.scoreData) {
            if (question.multiple) {
              this.$set(question, 'checkList', [])
            }
          }
        }
      }
    },
    cleanDialog() {
      this.photoVisible = false
    },
    closeDialog() {
      this.$parent.previewDialogVisible = false

    },
    openedDialog() {
      var describeContentDiv = document.getElementById("describeContentDiv");
      let imgElementList = describeContentDiv.getElementsByTagName("img")
      console.log(imgElementList)
      for (let imgElement of imgElementList) {
        imgElement.addEventListener("click", (event) => {
          this.url = event.target.getAttribute('src')
          this.photoVisible = true;
        });
      }
      var resultDescriptionDiv = document.getElementById("resultDescriptionDiv");
      let resultDescriptionImgElementList = resultDescriptionDiv.getElementsByTagName("img")
      console.log(resultDescriptionImgElementList)
      for (let imgElement of resultDescriptionImgElementList) {
        imgElement.addEventListener("click", (event) => {
          this.url = event.target.getAttribute('src')
          this.photoVisible = true;
        });
      }

    },
    calculate() {
      this.resultFontColor = ''
      this.calculateResult = 0
      this.resultExplanation = 0
      try {
        // 公式类型计算得分;
        if (this.type == 1) {
          let cntExpression = ' ' + this.medicalCalculatorData[this.selectedFormulaExpressionIdx].calculateData.formulaExpressionItems[0].item_expression + ' '
          for (let cntItem of this.medicalCalculatorData[this.selectedFormulaExpressionIdx].calculateData.formulaItems) {
            let reg = new RegExp(`[^a-zA-Z]${cntItem.item_id}[^a-zA-Z]`)
            while (reg.test(cntExpression)) {
              let strOri = cntExpression.match(reg)[0]
              // 把所有字符都默认为1, eval计算 (1/0)结果为Infinity, 不会抛异常;
              let strNew = strOri.replace(cntItem.item_id, `(${cntItem.item_value})`)
              cntExpression = cntExpression.replace(strOri, strNew)
            }
          }
          // eval 计算, 如果表达式有误, 则抛异常;
          this.calculateResult = eval(cntExpression)
          // 保留两位有效数字;
          this.calculateResult = Math.round(this.calculateResult * 100) / 100
          // 与结果集比较;
          this.compareWithResultItems(this.calculateResult, this.medicalCalculatorData[this.selectedFormulaExpressionIdx].sections)
        }
        // 评分类型计算得分;
        else if (this.type == 2) {
          for (let question of this.calculatorSore[this.selectedFormulaExpressionIdx].scoreData) {
            for (let item of question.items) {
              if (question.multiple) {
                if (question.checkList.indexOf(item.id) != -1) {
                  this.calculateResult += parseFloat(item.score)
                }
              } else if (question.checkId == item.id) {
                this.calculateResult += parseFloat(item.score)
              }
            }
          }
          // 保留两位有效数字;
          this.calculateResult = Math.round(this.calculateResult * 100) / 100
          // 与结果集比较;
          this.compareWithResultItems(this.calculateResult, this.calculatorSore[this.selectedFormulaExpressionIdx].sections)
        }
        if (window.isNaN(this.calculateResult)) {
          throw '结果有误'
        }
        this.calculateResultDisplay = true
      } catch (e) {
        this.calculateResultDisplay = false
        alert('计算失败')
      }
    },
    compareWithResultItems(result, resultItems) {
      // 结果与结果集比较
      let relationArray = ['&&', '||']
      let conditionArray = ['>=', '>', '==', '<=', '<']
      for (let resultItem of resultItems) {
        let resultExpression = 'true'
        for (let condition of resultItem.sections) {
          resultExpression += relationArray[condition.relation] + '(' + this.calculateResult + ')' + conditionArray[condition.condition] + '(' + condition.value + ')'
        }
        let cntResultFlag = eval(resultExpression)
        if (cntResultFlag) {
          this.resultFontColor = resultColorMap[resultItem.result]
          this.resultExplanation = resultItem.explanation
          return
        }
      }
    }
  },
  watch: {
    scoreData: {
      handler(nv) {
        for (let question of nv) {
          if (question.multiple && !question.checkList) {
            this.$set(question, 'checkList', [])
          }
        }
      },
      deep: true
    },
  },
  data() {
    return {
      // "medicalCalculatorData": [],
      // "calculatorSore": [],
      // "describeContent": "<p>掌指关节（MP），近位指间关节（PIP），远位指间关节（DIP）主动屈曲度之和，减去各关节主动伸直受限度之和，即为该手指总主动活动度（TAM）。各关节伸直以0°为准，过伸部分不计。 TAM＝（MP＋PIP＋DIP）－（MP＋PIP＋DIP） 即，总主动活动度＝各关节屈曲度之和－各关节伸直受限度之和</p>",
      // "fields": [],
      // "type": 1,
      reference: '',
      resultDescription: '',
      visible: false,
      selectedFormulaExpressionIdx: 0,
      resultFontColor: '',
      calculateResult: 0,
      resultExplanation: '',
      activePanel: '',
      formulaName: '',
      calculateResultDisplay: false,
      url: '',
      photoVisible: false,
      name: '',
      formulaExplain: ''
    }
  },
  props: {
    medicalCalculatorData: {
      type: Array,
      default: function () {
        return []
      }
    },
    calculatorSore: {
      type: Array,
      default: function () {
        return []
      }
    },
    describeContent: {
      type: String,
    },
    fields: {
      type: Array,
      default: function () {
        return []
      }
    },
    type: {
      type: Number,
      default: 1
    },
    // resultItems: {
    //   type: Array,
    //   default: function () {
    //     return []
    //   }
    // },
    // resultDescription:{
    //   type: String
    // }
  },
}
</script>

<style scoped>

[v-cloak] {
  display: none;
}

/deep/ .el-dialog__body {
  padding-top: 0px;
}

/**
* 标题class
*/
#preview >>> .label {
  margin: 10px;
  font-size: large;
  font-weight: bold;
}

/**
* 警告文字
*/
#preview >>> .warning-text-cls {
  margin: 10px;
  font-size: 12px;
  color: red
}


/deep/ .el-radio-group {
  width: 100%;
}

/deep/ .el-radio-button {
  width: 50%;
}

/deep/ .el-radio-button__inner {
  width: 100%;
}

/**
* 计算/说明, 激活按钮;
*/
.el-radio-group > .is-active > .el-radio-button__inner {
  background-color: #2DB7A0 !important;
}

/**
* 计算/说明, 未激活按钮;
*/
.el-radio-group > :not(.is-active) > .el-radio-button__inner {
  background-color: #fff !important;
}

/**
* 计算方法, 公式计算, 评分计算... 文字前标记;
*/
#preview >>> .cal-method-tip,
#preview >>> .cal-tip,
#preview >>> .score-tip,
#preview >>> .cal-result-tip,
#preview >>> .desc-tip,
#preview >>> .result-desc-tip,
#preview >>> .reference-tip {
  width: 10px;
  height: 25px;
  border-radius: 5px;
  background-color: #2DB7A0;
  display: inline-block;
  vertical-align: text-bottom;
}

/**
* 计算方法, 公式计算, 评分计算...  标题文字;
*/
#preview >>> .cal-method-text-cls,
#preview >>> .cal-text-cls,
#preview >>> .score-text-cls,
#preview >>> .cal-result-text-cls,
#preview >>> .desc-text-cls,
#preview >>> .result-desc-text-cls,
#preview >>> .reference-text-cls {
  display: inline-block;
  font-size: large
}


/**
* 计算按钮;
*/
#preview >>> .cal-btn-class {
  color: #fff !important;
  border-color: #2DB7A0 !important;
  background-color: #2DB7A0 !important;
}

/**
* 参考文献内容
*/
#preview >>> .reference-content {
  margin: 15px
}

/**
* 列项文字
*/
#preview >>> .lx-text-cls {
  margin: 15px
}

.label {
  margin: 10px;
  font-size: large;
  font-weight: bold;
}

.warning-text-cls {
  margin: 10px;
  font-size: 12px;
  color: red
}
</style>
